package com.efounder.util;

import android.annotation.SuppressLint;
import android.app.ProgressDialog;
import android.content.Context;
import android.content.DialogInterface;
import android.content.DialogInterface.OnDismissListener;
import android.content.Intent;
import android.content.pm.PackageManager;
import android.content.pm.ResolveInfo;
import android.net.Uri;
import android.os.AsyncTask;
import android.util.Log;
import android.view.Gravity;
import android.widget.Toast;

import androidx.annotation.Nullable;

import com.efounder.ospmobilelib.R;
import com.efounder.tbs.DisplayFileWithTbsUtil;
import com.efounder.utils.ResStringUtil;
import com.pansoft.resmanager.ResFileManager;
import com.utilcode.util.UriUtils;

import org.apache.http.HttpEntity;
import org.apache.http.HttpResponse;
import org.apache.http.HttpStatus;
import org.apache.http.client.CookieStore;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.impl.client.DefaultHttpClient;

import java.io.File;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.UnsupportedEncodingException;
import java.lang.reflect.Field;
import java.net.URLDecoder;
import java.net.URLEncoder;
import java.util.List;

/**
 * 国勘OA详情页面 点击附件 下载并打开附件
 *
 * @author cherise
 */
@SuppressLint("DefaultLocale")
public class DownAttachGKUtil {

    private String directory;
    private Context mcontext;
    private String url;
    private String mcookie;

    private final String FRONTURL = "https://gkyd.zyof.com.cn/ESPWTN/servlet/DownLoad?cookie=&url=";
    private final String FFSFRONTURL = "https://gkyd.zyof.com.cn/ESPWTN/servlet/DownLoad2?cookie=";
    private final String GKOAFRONTURL = "https://gkyd.zyof.com.cn/ESPWTN/servlet/DownLoad?cookie=&url=";


    public DownAttachGKUtil(Context mcontext, String url, String cookie) {
        super();
        this.mcontext = mcontext;
        this.url = FRONTURL + url;
        this.mcookie = cookie;
        directory = ResFileManager.MEETING;
        File file = new File(directory);
        if (!file.exists() && !file.isDirectory()) {
            System.out.println("//不存在");
            file.mkdir();
        } else {
            System.out.println("//目录存在");
        }

    }

    //重点任务附件
    public DownAttachGKUtil(Context mcontext, String url) {
        super();
        this.mcontext = mcontext;
        this.url = url;
        directory = ResFileManager.MEETING;
        File file = new File(directory);
        if (!file.exists() && !file.isDirectory()) {
            System.out.println("//不存在");
            file.mkdir();
        } else {
            System.out.println("//目录存在");
        }

    }

    /**
     * 此方法是给费用报销和请销假下载附件使用的
     *
     * @param mcontext
     * @param url
     * @param cookie
     * @param systemType
     */
    public DownAttachGKUtil(Context mcontext, String url, String cookie,
                            String systemType) {
        super();
        this.mcontext = mcontext;
        this.mcookie = cookie;
        try {
            url = URLEncoder.encode(url, "GBK");
            cookie = URLEncoder.encode(cookie, "GBK");
        } catch (UnsupportedEncodingException e) {
            e.printStackTrace();
        }
        if ("GKOA".equals(systemType)) {
            this.url = GKOAFRONTURL + url;// 国勘OA附件下载
        } else {//ffs 费用报销
            this.url = FFSFRONTURL + cookie + "&url=" + url;
            // this.url = FFSFRONTURL + url;
            Log.i("url:", this.url);

        }


        directory = ResFileManager.MEETING;
        File file = new File(directory);
        if (!file.exists() && !file.isDirectory()) {
            System.out.println("//不存在");
            file.mkdirs();
        } else {
            System.out.println("//目录存在");
        }

    }

    /**
     * 执行下载
     */
    public void taskStart() {
        DownloaderTask task = new DownloaderTask();
        task.execute(url);

    }

    public void taskStartWithKeyTask() {
        DownloaderTask task = new DownloaderTask(true);
        task.execute(url);

    }

    // 内部类
    private class DownloaderTask extends AsyncTask<String, Void, String> {
        private boolean isKeyTask = false;

        public DownloaderTask() {
        }

        public DownloaderTask(boolean isKeyTask) {
            this.isKeyTask = isKeyTask;
        }

        @SuppressWarnings("deprecation")
        @Override
        protected String doInBackground(String... params) {
            return downFile(params[0], isKeyTask);
        }

        @Nullable
        private String downFile(String param, boolean isKeyTask) {
            String url = param;
            String fileName = System.currentTimeMillis() + "";
            fileName += url.substring(url.lastIndexOf("."));

            fileName = URLDecoder.decode(fileName);
            Log.i("tag", "fileName=" + fileName);
            File file = new File(directory, fileName);

            try {
                DefaultHttpClient client = new DefaultHttpClient();
                HttpGet get = new HttpGet(url);

                if (isKeyTask) {//重点任务附件下载
                    Class clazz = Class.forName("com.efounder.guokan.manager.KeyTaskCasLoginManager");
                    Field field = clazz.getField("TASK_COOKIESTORE");
                    CookieStore cookieStore = (CookieStore) field.get(clazz);
                    client.setCookieStore(cookieStore);
                } else {
                    get.addHeader("cookie", mcookie);
                }
                HttpResponse response = client.execute(get);

                if (HttpStatus.SC_OK == response.getStatusLine()
                        .getStatusCode()) {
                    HttpEntity entity = response.getEntity();
                    InputStream input = entity.getContent();

                    writeToSDCard(fileName, input);

                    input.close();
                    // entity.consumeContent();
                    return fileName;
                } else {
                    return null;
                }
            } catch (Exception e) {
                e.printStackTrace();
                return null;
            }
        }

        @Override
        protected void onCancelled() {
            // TODO Auto-generated method stub
            super.onCancelled();
        }

        @Override
        protected void onPostExecute(String result) {
            // TODO Auto-generated method stub
            super.onPostExecute(result);
            closeProgressDialog();
            if (result == null) {
                Toast t = Toast.makeText(mcontext, ResStringUtil.getString(R.string.common_text_connect_error),
                        Toast.LENGTH_LONG);
                t.setGravity(Gravity.CENTER, 0, 0);
                t.show();
                return;
            }

//            Toast t = Toast.makeText(mcontext, "已保存到SD卡", Toast.LENGTH_SHORT);
//            t.setGravity(Gravity.CENTER, 0, 0);
//            t.show();
            // File directory=Environment.getExternalStorageDirectory();
            File file = new File(directory, result);
            Log.i("tag", "Path=" + file.getAbsolutePath());

            try {

                if (DisplayFileWithTbsUtil.displayFile(mcontext, file.getAbsolutePath())) {
                    return;
                }
                Intent intent = getFileIntent(file);
                if (isIntentAvailable(mcontext, intent)) {
                    mcontext.startActivity(intent);
                } else {
                    Toast t1 = Toast.makeText(mcontext, "请安装该文件类型的程序！",
                            Toast.LENGTH_LONG);
                    t1.setGravity(Gravity.CENTER, 0, 0);
                    t1.show();
                }
            } catch (Exception e) {
                Toast t2 = Toast.makeText(mcontext,
                        "该文件打开失败，请检查手机是否存在打开该文件类型的程序。", Toast.LENGTH_LONG);
                t2.setGravity(Gravity.CENTER, 0, 0);
                t2.show();
            }

        }

        @Override
        protected void onPreExecute() {
            // TODO Auto-generated method stub
            super.onPreExecute();
            showProgressDialog();
        }

        @Override
        protected void onProgressUpdate(Void... values) {
            // TODO Auto-generated method stub
            super.onProgressUpdate(values);
        }

    }

    private ProgressDialog mDialog;

    private void showProgressDialog() {
        if (mDialog == null) {
            mDialog = new ProgressDialog(mcontext);
            mDialog.setProgressStyle(ProgressDialog.STYLE_SPINNER);// 设置风格为圆形进度条
            mDialog.setMessage(ResStringUtil.getString(R.string.common_text_please_wait));
            mDialog.setIndeterminate(false);// 设置进度条是否为不明确
            mDialog.setCancelable(true);// 设置进度条是否可以按退回键取消
            mDialog.setCanceledOnTouchOutside(false);
            mDialog.setOnDismissListener(new OnDismissListener() {

                @Override
                public void onDismiss(DialogInterface dialog) {
                    // TODO Auto-generated method stub
                    mDialog = null;
                }
            });
            mDialog.show();

        }
    }

    private void closeProgressDialog() {
        try {
            if (mDialog != null) {
                if (mcontext != null) {
                    mDialog.dismiss();
                }
                mDialog = null;
            }
        } catch (Exception e) {
            mDialog = null;
            e.printStackTrace();
        }
    }

    public Intent getFileIntent(File file) {
        // Uri uri = Uri.parse("http://m.ql18.com.cn/hpf10/1.pdf");
        Uri uri = UriUtils.getUriForFile(file);
        String type = getMIMEType(file);
        Log.i("tag", "type=" + type);
        Intent intent = new Intent("android.intent.action.VIEW");
        intent.addFlags(Intent.FLAG_GRANT_READ_URI_PERMISSION);
        intent.addCategory("android.intent.category.DEFAULT");
        intent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
        intent.setDataAndType(uri, type);
        return intent;
    }

    public void writeToSDCard(String fileName, InputStream input) {

        File file = new File(directory, fileName);
        try {
            FileOutputStream fos = new FileOutputStream(file);
            byte[] b = new byte[2048];
            int j = 0;
            while ((j = input.read(b)) != -1) {
                fos.write(b, 0, j);
            }
            fos.flush();
            fos.close();
        } catch (FileNotFoundException e) {
            e.printStackTrace();
        } catch (IOException e) {
            e.printStackTrace();
        }
    }

    private String getMIMEType(File f) {
        String type = "";
        String fName = f.getName();
        /* 取得扩展名 */
        String end = fName
                .substring(fName.lastIndexOf(".") + 1, fName.length())
                .toLowerCase();

        /* 依扩展名的类型决定MimeType */
        if (end.equals("pdf")) {
            type = "application/pdf";//
        } else if (end.equals("m4a") || end.equals("mp3") || end.equals("mid")
                || end.equals("xmf") || end.equals("ogg") || end.equals("wav")) {
            type = "audio/*";
        } else if (end.equals("3gp") || end.equals("mp4")) {
            type = "video/*";
        } else if (end.equals("jpg") || end.equals("gif") || end.equals("png")
                || end.equals("jpeg") || end.equals("bmp")) {
            type = "image/*";
        } else if (end.equals("apk")) {
            /* android.permission.INSTALL_PACKAGES */
            type = "application/vnd.android.package-archive";
        } else if (end.equals("pptx") || end.equals("ppt")) {
            type = "application/vnd.ms-powerpoint";
        } else if (end.equals("docx") || end.equals("doc")) {
            type = "application/msword";
        } else if (end.equals("xlsx") || end.equals("xls")) {
            type = "application/vnd.ms-excel";
        } else {
            // /*如果无法直接打开，就跳出软件列表给用户选择 */
            type = "*/*";
        }
        return type;
    }

    /**
     * 判断Intent 是否存在 防止崩溃
     *
     * @param context
     * @param intent
     * @return
     */
    private boolean isIntentAvailable(Context context, Intent intent) {
        final PackageManager packageManager = context.getPackageManager();
        List<ResolveInfo> list = packageManager.queryIntentActivities(intent,
                PackageManager.GET_ACTIVITIES);
        return list.size() > 0;
    }

}
